package com.steshov.trainer.utils;

import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.steshov.trainer.activities.Index;
import com.steshov.trainer.dao.TaskDAO;
import com.steshov.trainer.model.Task;

public class ExerciseGenerator extends AsyncTask<String, Void, Boolean> {

	long currentTime = new Date().getTime();
	long period = 1800000;
	final int LOW = 20;
	final int MID = 40;
	final int HIGH = 60;
	final int numberOfTasks = 4;
	final byte generated = 1;
	TaskDAO taskDao = new TaskDAO();
	Index context;
	private ProgressDialog dialog;

	public ExerciseGenerator(Index context) {
		this.context = context;
		dialog = new ProgressDialog(context);
	}

	protected void onPreExecute() {
		dialog.setMessage("Generating");
		dialog.show();
	}

	private void generate() {
		ArrayList<Task> tasks = new ArrayList<Task>();
		String[] exercises = taskDao.getExercises(context);
		String level = context.getStressLevel();

		for (int i = 0; i < numberOfTasks; i++) {
			Random rand = new Random();
			int exerciseNumber = rand.nextInt(exercises.length);
			Task task = new Task(null, exercises[exerciseNumber], 0,
					currentTime + period);
			task.setGenerated(generated);
			switch (Stress.valueOf(level)) {
			case GREEN:
				task.setAmount(LOW + exerciseNumber);
				break;
			case YELLOW:
				task.setAmount(MID + exerciseNumber);
				break;
			case RED:
				task.setAmount(HIGH + exerciseNumber);
				break;
			}
			tasks.add(task);
			period += period;
		}
		for (Task task : tasks) {
			taskDao.peristTask(context, task, false);
		}
	}

	private void removeGenerated() {
		taskDao.removeGenerated(context);
	}

	@Override
	protected Boolean doInBackground(String... args) {
		if (App.generateButtonFlag == true) {
			generate();

		} else if (App.generateButtonFlag == false) {
			removeGenerated();
		}
		return true;
	}

	@Override
	protected void onPostExecute(final Boolean success) {

		if (dialog.isShowing()) {
			dialog.dismiss();
		}
	}
}
